import datetime
from django.http import JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse_lazy
from rest_framework.views import APIView
from lottery.models import CollectionInfoModels, LotteryTheme


class SubmitSuccessView(APIView):

    def get(self, request, *args, **kwargs):
        qs = LotteryTheme.objects.filter(is_now=True)
        # 获取当期那的时间
        now_time = datetime.datetime.now()
        if qs.exists():
            # 获取数据库设置的开奖时间
            open_time = qs.first().draw_at
            limit_time = datetime.datetime.strptime(open_time, '%Y-%m-%d %H:%M:%S') - now_time
            left_time = limit_time.total_seconds()
            people_number = qs.first().people_number + 5000
        else:
            left_time = 0
            people_number = 5000
        return render(request, 'success.html', locals())


class SearchResultView(APIView):

    def get(self, request, *args, **kwargs):
        search_emial = request.query_params.get("email", '')
        fiter_qs = CollectionInfoModels.objects.filter(email=search_emial)
        data = {'msg': '', 'code': 200}
        if not fiter_qs.exists():
            data['msg'] = "Unfortunately! You are participating in this lucky draw!"
            data['code'] = 500
            return JsonResponse(data)
        now_time = datetime.datetime.now()
        if now_time.strftime('%Y-%m-%d %H:%M:%S') <= fiter_qs.first().theme.draw_at:
            data['msg'] = "The draw date has not arrived! Please come back later!"
            data['code'] = 500
            return JsonResponse(data)
        is_hooks = fiter_qs.first().is_hook
        if is_hooks:
            data['msg'] = 'Congratulations! you won the lottery!'
            data['code'] = 200
            data['user_id'] = fiter_qs.first().id
        else:
            data['msg'] = 'Unfortunately, you did not win the prize!'
            data['code'] = 500

        return JsonResponse(data)


class SearchPage(APIView):

    def get(self, request, *args, **kwargs):
        qs = LotteryTheme.objects.filter(is_now=True)
        # 获取当期那的时间
        now_time = datetime.datetime.now()
        if qs.exists():
            # 获取数据库设置的开奖时间
            open_time = qs.first().draw_at
            limit_time = datetime.datetime.strptime(open_time, '%Y-%m-%d %H:%M:%S') - now_time
            left_time = limit_time.total_seconds()
            people_number = qs.first().people_number + 5000
        else:
            left_time = 0
            people_number = 5000
        return render(request, 'search.html', locals())


class LotteryIndexView(APIView):
    """
        环节主要代码
    """

    def get(self, request, *args, **kwargs):
        qs = LotteryTheme.objects.filter(is_now=True)
        # 获取当期那的时间
        now_time = datetime.datetime.now()
        if qs.exists():
            # 获取数据库设置的开奖时间
            open_time = qs.first().draw_at
            limit_time = datetime.datetime.strptime(open_time, '%Y-%m-%d %H:%M:%S') - now_time
            left_time = limit_time.total_seconds()
            people_number = qs.first().people_number + 5000
        else:
            left_time = 0
            people_number = 5000

        show = request.query_params.get("flag", False)
        return render(request, 'index.html', locals())

    def post(self, request, *args, **kwargs):
        # 当钱激活的抽奖
        now_lottory = LotteryTheme.objects.filter(is_now=True).first()
        data = {
            "full_name": request.data.get("full_name", ""),
            "email": request.data.get("email", ""),
            "telegram_username": request.data.get("telegram_username", ""),
            "bep_wallet_address": request.data.get("bep_wallet_address", ""),
            "theme": now_lottory
        }
        if not CollectionInfoModels.objects.filter(email=request.data.get('email')).exists():
            CollectionInfoModels.objects.create(**data)
            now_lottory.people_number += 1
            now_lottory.save()
            return redirect('/success')
        else:
            return redirect('/index/?flag=True')


class ShowPageView(APIView):

    def get(self, request, *args, **kwargs):
        qs = LotteryTheme.objects.filter(is_now=True)
        # 获取当期那的时间
        now_time = datetime.datetime.now()
        if qs.exists():
            # 获取数据库设置的开奖时间
            open_time = qs.first().draw_at
            limit_time = datetime.datetime.strptime(open_time, '%Y-%m-%d %H:%M:%S') - now_time
            left_time = limit_time.total_seconds()
            people_number = qs.first().people_number + 5000
            contract_address = qs.first().contract_address
        else:
            left_time = 0
            people_number = 5000
            contract_address = ""
        return render(request, 'showpage.html', locals())

    def post(self, request, *args, **kwargs):
        user_id = request.query_params.get("user_id")
        data = {
            'telegram_username': request.data.get("a"),
            'bep_wallet_address': request.data.get("b")
        }
        CollectionInfoModels.objects.filter(id=user_id).update(**data)
        return JsonResponse({"code": 200, "msg": "Commit information Success!"})